package com.bw.ivideo.ui

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.ivideo.BuildConfig
import com.bw.ivideo.R
import com.bw.ivideo.adapter.FragmentAdapter
import com.bw.ivideo.appversion.intent.VersionIntent
import com.bw.ivideo.appversion.state.VersionState
import com.bw.ivideo.appversion.viewmodel.AppVersionViewModel
import com.bw.ivideo.common.ConstanstValue
import com.bw.ivideo.databinding.ActivityHomeBinding
import com.bw.lib_common.arout.ARouterPath
import com.bw.lib_mvicore.ui.BaseActivity
import com.bw.lib_mvicore.ui.BaseMviActivity
import com.bw.lib_widget.dialog.AppUpdateDialog
import com.bw.lib_widget.dialog.BaseDialog
import com.google.android.material.badge.BadgeDrawable
import com.google.android.material.navigation.NavigationBarView
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = ConstanstValue.APP_HOMEACTIVITY_PATH)
class HomeActivity : BaseMviActivity() {

    private lateinit var binding: ActivityHomeBinding
    private val list: MutableList<Fragment> = mutableListOf()
    private lateinit var fragmentAdapter: FragmentAdapter
    private lateinit var viewModel: AppVersionViewModel

    override fun getLayoutView(): View {
        binding = ActivityHomeBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                viewModel.state.collect{
                    when(it){
                        is VersionState.Init -> {}
                        is VersionState.Success -> {
                            showAppVersionDialog(it)
                        }
                        is VersionState.Error -> {

                        }
                    }
                }
            }
        }
    }

    private fun showAppVersionDialog(it: VersionState.Success) {
        if(it.data.status){
            AppUpdateDialog.Builder(this)
                .setContent(it.data.new_version, it.data.updated_details)
                .setListener(object : AppUpdateDialog.OnListener{
                    override fun onSelected(dialog: BaseDialog?) {
                        showMsg("下载App")
                    }

                    override fun onCancel(dialog: BaseDialog?) {
                        showMsg("取消升级")
                    }
                }).show()
        }
    }

    override fun initView() {
        super.initView()
        getFragments()

        fragmentAdapter = FragmentAdapter(list, supportFragmentManager)
        binding.vpHome.adapter = fragmentAdapter

        //红点
        binding.bnvHome.labelVisibilityMode = NavigationBarView.LABEL_VISIBILITY_AUTO
        val badge = binding.bnvHome.getOrCreateBadge(3)
        badge.badgeGravity = BadgeDrawable.TOP_END
        badge.isVisible = true
        badge.number = 90

    }

    override fun initData() {
        super.initData()
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                val map = mutableMapOf<String, String>()
                map["app_id"] = "0"
                map["versionCode"] = BuildConfig.VERSION_CODE.toString()
                map["versionName"] = BuildConfig.VERSION_NAME
                viewModel.intents.send(VersionIntent.GetAppVersionIntent(map))
            }
        }
    }

    private fun getFragments() {
        val homeFragment = ARouter.getInstance().build(ARouterPath.HOME_PATH).navigation() as Fragment
        list.add(homeFragment)
        val cinemaFragment = ARouter.getInstance().build(ARouterPath.CINEMAMA_PATH).navigation() as Fragment
        list.add(cinemaFragment)
        val publishFragment = ARouter.getInstance().build(ARouterPath.PUBLISH_PATH).navigation() as Fragment
        list.add(publishFragment)
        val liveFragment = ARouter.getInstance().build(ARouterPath.LIVE_PATH).navigation() as Fragment
        list.add(liveFragment)
        val mineFragment = ARouter.getInstance().build(ARouterPath.MINE_PATH).navigation() as Fragment
        list.add(mineFragment)
    }

    override fun generateViewModel() {
        viewModel = ViewModelProvider(this)[AppVersionViewModel::class.java]
    }

    override fun initEvent() {
        super.initEvent()
        binding.bnvHome.setOnItemSelectedListener {
            when(it.itemId){
                R.id.bar_home -> {
                    binding.vpHome.setCurrentItem(0, false)
                }
                R.id.bar_cinema -> {
                    binding.vpHome.setCurrentItem(1,false)
                }
                R.id.bar_send -> {
                    binding.vpHome.setCurrentItem(2,false)
                }
                R.id.bar_msg -> {
                    binding.vpHome.setCurrentItem(3,false)
                }
                R.id.bar_mine->{
                    val userInfo = MMKV.defaultMMKV().decodeString("userInfo")
                    if (TextUtils.isEmpty(userInfo)) {
                        routeToLogin()
                        binding.vpHome.currentItem = 3
                    }else{
                        binding.vpHome.setCurrentItem(4,false)
                    }

                }
                else -> {

                }
            }
            //!!!!注意!!!!!!!!
            return@setOnItemSelectedListener true
        }

        binding.vpHome.addOnPageChangeListener(object : OnPageChangeListener{
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                /**
                 * 处理用户登录问题
                 */
                if (position == 4){
                    val userInfo = MMKV.defaultMMKV().decodeString("userInfo")
                    if (TextUtils.isEmpty(userInfo)){
                        routeToLogin()
                        binding.vpHome.currentItem = 3
                        return
                    }
                }
                binding.bnvHome.menu.getItem(position).isChecked = true
            }

            override fun onPageScrollStateChanged(state: Int) {

            }

        })

    }

    private fun routeToLogin() {
        ARouter.getInstance().build(ConstanstValue.APP_LOGIN_PATH)
            .withTransition(com.bw.lib_common.R.anim.slide_in_from_right, com.bw.lib_common.R.anim.slide_out_from_left)
    }

}